package edu.zju.gis.dbfg.common.base;

import com.github.pagehelper.PageHelper;
import edu.zju.gis.dbfg.common.Page;
import edu.zju.gis.dbfg.common.constant.DaoMethod;
import edu.zju.gis.dbfg.common.exception.DaoException;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * Service基类，实现了数据的CRUD
 *
 * @param <Mapper>
 * @param <T>
 * @param <ID>
 * @author Hu
 */
public abstract class BaseServiceImpl<Mapper extends BaseMapper<T, ID>, T, ID extends Serializable>
        implements BaseService<T, ID> {

    /**
     * 由子类注入mapper
     */
    @Autowired
    public Mapper mapper;

    @Override
    public Page<T> search(BaseFilter params, Page page) {
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        return new Page<T>(mapper.search(params));
    }

    /**
     * 通过主键查询实体
     *
     * @param pk
     * @return T
     */
    @Override
    public T select(ID pk) {
        T t = mapper.select(pk);
        if (t == null) throw new DaoException(DaoMethod.READ, this.getClass().toString() + ".select", pk.toString());
        return t;
    }

    /**
     * 插入实体
     *
     * @param t
     */
    @Override
    public int save(T t) {
        return verifyRows(t, DaoMethod.CREATE, 1, mapper.insert(t));
    }


    /**
     * 更新实体
     *
     * @param t
     */
    @Override
    public int update(T t) {
        return verifyRows(t, DaoMethod.UPDATE, mapper.update(t), 1);
    }


    /**
     * 通过主键删除实体
     *
     * @param id
     * @return T
     */
    @Override
    public int delete(ID id) {
        return mapper.delete(id);
    }

    @Override
    public int delete(List<ID> ids) {
        return mapper.deleteBatch(ids);
    }

    @Override
    public boolean isExist(ID id) {
        T t = select(id);
        return !(t==null);
    }

    /**
     * 验证更新数据库记录条数
     * @param method
     * @param updateRows
     * @param rows
     * @return
     */
    protected int verifyRows(T t, DaoMethod method, int updateRows, int rows) {
        if (updateRows != rows) {
            throw new DaoException(method, t.getClass().toString(), t.toString());
        }
        return updateRows;
    }
}
